package com.lvan.service.common;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lvan.bean.BaseException;
import com.lvan.bean.Page;
import com.lvan.bean.Product;
import com.lvan.constant.ValidateRecord;
import com.lvan.dao.mapper.ProductMapper;
import com.lvan.service.AbstractService;
import com.lvan.service.interfaze.common.IProductService;
import com.lvan.util.InputValidate;

@Service("productService")
public class ProductService extends AbstractService implements IProductService {
	@Autowired
	private ProductMapper productMapper;
	private InputValidate<Product> validator = new InputValidate<Product>();
	@Override
	public void add(Product p) throws BaseException {
		Set<ValidateRecord> constraintViolations = validator.validate(p,true);
        if (!constraintViolations.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (ValidateRecord record : constraintViolations) {
                sb.append(record.getMessage()+"; ");
            }
            throw new BaseException("",REQUEST_PARAM_ERROR,sb.toString());
        }
        productMapper.add(p);
	}

	@Override
	public void delete(Serializable ids) throws BaseException {
		if(ids!=null) {
			productMapper.delete(ids);
		}
	}

	@Override
	public void update(Product p) throws BaseException {
		Set<ValidateRecord> constraintViolations = validator.validate(p,false);
        if (!constraintViolations.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (ValidateRecord record : constraintViolations) {
                sb.append(record.getMessage()+"; ");
            }
            throw new BaseException("",REQUEST_PARAM_ERROR,sb.toString());
        }
        productMapper.update(p);
	}

	@Override
	public Product getByID(Serializable id) {
		return productMapper.getByID(id);
	}

	@Override
	public int count(Product p) {
		return productMapper.count(p);
	}

	@Override
	public List<Product> query(Product p, Page page) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("product", p);
		params.put("page", page.getPageSql());
		params.put("orderBy", p.convertField2Column());
		page.setTotal(this.count(p));
        return productMapper.query(params);
	}

}
